import { ref, watch } from 'vue'
import store from '@/store'
import Configuration from '@/api/client/configuration.js'
import message from 'ant-design-vue/lib/message/index.js'
import { SAVED_SUCCESSFULLY } from '@/constants/message.js'

export function useConfigurationItems(id) {
  store.dispatch('dict/getHROrg')
  const configurationItemsLoading = ref(true)
  const configurationItems = ref([])
  const configurationItemsTemp = ref([])
  const loadConfigurationItems = () => {
    Configuration.getClientOrg(id)
      .then(({ data }) => {
        configurationItems.value = data
      })
      .finally(() => {
        configurationItemsLoading.value = false
      })
  }
  loadConfigurationItems()
  const showConfigurationItemsModal = ref(false)
  watch(
    () => showConfigurationItemsModal.value,
    () => {
      configurationItemsTemp.value = configurationItems.value.map(item => item.Value)
    }
  )
  const handleSaveConfigurationItems = async () => {
    await Configuration.saveClientOrg(id, configurationItemsTemp.value)
    message.success(SAVED_SUCCESSFULLY)
    loadConfigurationItems()
    showConfigurationItemsModal.value = false
  }
  return {
    showConfigurationItemsModal,
    configurationItems,
    configurationItemsLoading,
    configurationItemsTemp,
    handleSaveConfigurationItems,
    loadConfigurationItems
  }
}
